package term

import (
	"context"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/attachment/model"
	"mall/service/attachment/rpc/internal/svc"
	"mall/service/attachment/rpc/internal/utils"
	"mall/service/attachment/rpc/internal/utils/errorhandler"
	"mall/service/attachment/rpc/types/attachment"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetTermByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetTermByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetTermByIdLogic {
	return &BackendGetTermByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetTermByIdLogic) BackendGetTermById(in *attachment.TermIdReq) (*attachment.TermInfo, error) {
	if in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	res, err := l.svcCtx.MediaTerm.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var meta []*attachment.MetaInfo
	if in.WithMeta != nil && *in.WithMeta > 0 {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.AttachmentTermMetumColumns.TermID] = map[string][]any{
			"equalTo": []any{in.Id},
		}
		list, _, err := l.svcCtx.MediaTerm.GetMeta(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 {
			for _, v := range list {
				if len(v.MetaKey) > 0 && v.MetaValue.Valid {
					meta = append(meta, &attachment.MetaInfo{
						Id:    pointy.GetPointer(v.MetaID),
						Key:   pointy.GetPointer(v.MetaKey),
						Value: pointy.GetPointer(v.MetaValue.String),
					})
				}
			}
		}
	}

	return &attachment.TermInfo{
		Id:           pointy.GetPointer(res.TermID),
		Name:         pointy.GetPointer(res.Name),
		Slug:         pointy.GetPointer(res.Slug),
		Taxonomy:     pointy.GetPointer(utils.FormatTaxonomy(int32(res.Taxonomy))),
		ParentId:     pointy.GetPointer(res.ParentID),
		GroupId:      pointy.GetPointer(uint32(res.TermGroup)),
		Desc:         pointy.GetPointer(res.Description),
		FilteredDesc: pointy.GetPointer(res.DescriptionFiltered),
		Sort:         pointy.GetPointer(uint32(res.Sort)),
		Status:       pointy.GetPointer(uint32(res.Status)),
		Count:        pointy.GetPointer(uint32(res.Count)),
		CreatedAt:    pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt:    pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt:    pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
		Meta:         meta,
	}, nil
}
